package com.company.restaurant.service.session;

import io.netty.channel.ChannelHandlerContext;

import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Description of class.
 * Created 3/26/14 5:54 PM
 *
 * @author andrey.rodin@playtech.com
 */

public class SessionManager {

    private static ConcurrentHashMap<String, TcpClientSession> sessions = new ConcurrentHashMap<>();
    private static ConcurrentHashMap<ChannelHandlerContext, TcpClientSession> sessionsContext = new ConcurrentHashMap<>();

    public static String addNewSession(TcpClientSession session) {
        String uuid = UUID.randomUUID().toString();
        session.setToken(uuid);
        session.setCreateDate(System.currentTimeMillis());
        sessions.put(uuid, session);
        sessionsContext.put(session.getChannel(), session);
        return uuid;
    }

    public static TcpClientSession getSession(String token) {
        TcpClientSession clientSession = sessions.get(token);
        clientSession.setLastUpdate(System.currentTimeMillis());
        return clientSession;
    }

    public static TcpClientSession getSession(ChannelHandlerContext context) {
        return sessionsContext.get(context);
    }

    public static void removeSession(String token) {
        TcpClientSession clientSession = sessions.remove(token);
        sessionsContext.remove(clientSession.getChannel());
    }

    public static void removeSession(ChannelHandlerContext context) {
        TcpClientSession clientSession = sessionsContext.remove(context);
        sessions.remove(clientSession.getToken());
    }
}
